package com.ITD.handler;

import com.ITD.utils.JWTUtils;
import com.ITD.vo.ErrorCode;
import com.ITD.vo.Result;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取权限值
        String authorization = request.getHeader("Authorization");

        //根据token：判断是否有key/判断该key是否有值
        if(Boolean.FALSE.equals(redisTemplate.hasKey("TOKEN_"+authorization))) {
            //编写返回数据
            Result result= Result.fail(ErrorCode.EXPIRE_TOKEN.getCode(), ErrorCode.EXPIRE_TOKEN.getMsg(), "token过期");

            //输出返回结果，非return
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JSON.toJSONString(result));
            return false;
        }

        //检验token解析结果
        Map<String, Object> Map = JWTUtils.checkToken(authorization);
        if(Map==null){
            //编写返回数据
            Result result= Result.fail(ErrorCode.USER_NO_EXIST.getCode(), ErrorCode.USER_NO_EXIST.getMsg(), "用户不存在");

            //输出返回结果，非return
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JSON.toJSONString(result));
            return false;
        }

        return true;
    }

    }
